package credit

import (
	"context"
	"fmt"
	"github.com/ethereum/go-ethereum/accounts/abi/bind"
	"github.com/ethereum/go-ethereum/common"
	"github.com/ethereum/go-ethereum/ethclient"
	"log"
	"math/big"
	"os"
	"photo_credit/eths"
)

const (
	ContractAddr = "0x25AC36A46786055fAffb15854a1c1702905F1B94"
)

//Geth客户端全局连接句柄
var ethcli *ethclient.Client

// ConTract 合约全局实例
var ConTract *eths.Credit

// Opts 操作者实例
var Opts *bind.TransactOpts

func init() {
	cli, err := ethclient.Dial("http://localhost:8545")
	if err != nil {
		log.Panic("Failed to ethclient.Dial ", err)
	}
	ethcli = ethcli
	//构造合约实例
	instance, err := eths.NewCredit(common.HexToAddress(ContractAddr), cli)
	if err != nil {
		log.Panic("Failed to NewPxa721", err)
	}
	ConTract = instance

	//构造交易者
	keyfile := "D:\\##CODE##\\毕业设计\\geth\\rungeth-master\\devdata\\keystore\\UTC--2022-03-05T16-00-42.226441200Z--878f3b64b7728a11c7d713dc4928f8c46f021f05"
	reader, _ := os.Open(keyfile)
	opts, err2 := bind.NewTransactor(reader, "123")
	if err != nil {
		fmt.Println(err)
	}
	if err2 != nil {
		fmt.Println(err2)
	}
	Opts = opts

	gasPrice, err := cli.SuggestGasPrice(context.Background())
	opts.GasPrice = gasPrice
}

// GetCreditClient 获取客户端实例
func GetCreditClient() *eths.Credit {
	return ConTract
}

// Approve 图片授权
func Approve(user string, token *big.Int) (err error) {
	_, err = ConTract.Approve(Opts, user, token)
	return
}

// TransferToken 资产转移
func TransferToken(from string, to string, token *big.Int) (err error) {
	_, err = ConTract.TransferToken(Opts, from, to, token)
	return
}
